// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.modules.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.liuxinlong.api.SPOInterface;
import com.liuxinlong.api.SPORequestHeaderDto;
import com.liuxinlong.api.SharePoint;
import com.liuxinlong.common.AosException;
import com.liuxinlong.common.SnowFlake;
import com.liuxinlong.constant.ThreadLocalConstants;
import com.liuxinlong.constant.TimeFormatConstants;
import com.liuxinlong.enums.FileBusinessTypeEnum;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.dao.DataPushDao;
import com.liuxinlong.modules.dao.FileManageDao;
import com.liuxinlong.modules.dao.FileTemporaryDao;
import com.liuxinlong.modules.dao.StandardDao;
import com.liuxinlong.modules.dao.UserDao;
import com.liuxinlong.modules.dao.UserGroupDao;
import com.liuxinlong.modules.dao.UserGroupRelationDao;
import com.liuxinlong.modules.dao.UserStandardPermissionDao;
import com.liuxinlong.modules.entity.DataPushRecord;
import com.liuxinlong.modules.entity.FileManage;
import com.liuxinlong.modules.entity.FileTemporary;
import com.liuxinlong.modules.entity.SharePointHeader;
import com.liuxinlong.modules.entity.Standard;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.modules.entity.UserGroup;
import com.liuxinlong.modules.entity.UserGroupRelation;
import com.liuxinlong.modules.entity.UserStandardPermission;
import com.liuxinlong.modules.mapper.SharePointHeaderMapper;
import com.liuxinlong.modules.system.service.FileManageService;
import com.liuxinlong.utils.IPUtils;
import com.liuxinlong.utils.ObjectUtils;
import com.liuxinlong.utils.ThreadlocalUtils;
import com.liuxinlong.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件管理服务层实现
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2022年2月9日
 */
@Service
@Slf4j
public class FileManegeServiceImpl implements FileManageService {
    @Autowired
    private FileManageDao fileManageDao;

    @Autowired
    private SPOInterface spoInterface;

    @Autowired
    private UserGroupRelationDao userGroupRelationDao;

    @Autowired
    private SharePointHeaderMapper sharePointHeaderMapper;

    @Autowired
    private FileTemporaryDao fileTemporaryDao;

    @Autowired
    private UserGroupDao userGroupDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private SharePoint sharePoint;

    @Autowired
    private StandardDao standardDao;

    @Autowired
    private UserStandardPermissionDao userStandardPermissionDao;

    @Autowired
    private DataPushDao dataPushDao;

    // 本地暂存上传文件路径
    private static String TEMP_LOCAL_FILE_PATH = "uploadSpo/";

    // 本地暂存上传文件路径
    private static String TRANSFER_LOCAL_FILE_PATH = "uploadTemp/";

    @Override
    public List<Map<String, Object>> queryFileList(Map<String, Object> queryParam) {
        List<FileManage> originList = fileManageDao.pageFileManageList(queryParam);
        int startNum = (int) queryParam.get("startNum");
        List<Map<String, Object>> resultList = completeResult(originList, startNum);
        return resultList;
    }

    @Override
    public int getFileCount(Map<String, Object> queryParam) {
        return fileManageDao.getFileManageCount(queryParam);
    }

    @Override
    public void addFileManage(FileManage fileManage) {
        fileManage.setId(SnowFlake.nextIdStr());
        fileManageDao.addFileManage(fileManage);
    }

    @Override
    public void updateFileManage(FileManage fileManage) {
        fileManageDao.updateFileManage(fileManage);
    }

    @Override
    public void deleteFileManage(String id) {
        FileManage fileManage = fileManageDao.selectById(id);
        if (ObjectUtils.isEmpty(fileManage)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "文件删除失败，文件信息不存在！");
        }
        if (fileManage.getBusinessType() == FileBusinessTypeEnum.DESIGN_STANDARD_MASTER.getValue()) {
            // 获取当前用户所在组,判断用户组查看权限
            User operateUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
            UserGroupRelation relation = userGroupRelationDao.queryRelationByInfo(operateUser.getId(), fileManage.getGroupId());
            if (ObjectUtils.isEmpty(relation)) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "文件删除失败，用户不具备该文件操作权限！");
            }
            SPORequestHeaderDto spo = getSpo(operateUser);
            spoInterface.removeFile(spo, fileManage.getFilePath());
        } else {
            File file = new File(fileManage.getFilePath());
            if (!file.delete()) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "文件删除失败");
            }
        }
        fileManage.setStatus(2);
        fileManageDao.updateById(fileManage);
    }

    @Override
    public Map<String, Object> queryFileManageInfos(String businessId) {
        Map<String, Object> resultMap = new HashMap<>();
        List<FileManage> originalList = fileManageDao.queryFileManageList(businessId);
        String currentIp = IPUtils.getCurrentIp();
        for (FileManage fileManage : originalList) {
            List<Map<String,Object>> businessFiles = new ArrayList<>();
            String businessType = String.valueOf(fileManage.getBusinessType());
            Map<String,Object> item = ObjectUtils.object2Map(fileManage);
            if (fileManage.getBusinessType() == FileBusinessTypeEnum.CHIMI_CARD_ATTACH.getValue() ||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.BUTLER_TRAIN_COVER.getValue() ||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.BUTLER_TRAIN_MAIN_PDF.getValue() ||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.BUTLER_TRAIN_ATTACH.getValue() ||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.FAQ_ATTACH.getValue() ||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.CAROUSEL_ATTACH.getValue() ||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.CAROUSEL_MOBILE_ATTACH.getValue() ||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.EXPERT_PICTURE.getValue() ||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.MESSAGE_PUSH_MEDIA.getValue() ||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.PATENT_TRENDS_PICTURE.getValue()||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.PATENT_CAROUSEL_ATTACH.getValue()||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.ASSETS_BUDGET_ATTACH.getValue()||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.PATENT_GOODS_IMPORT_ATTACH.getValue()||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.ASSETS_EXPENSE_ORDER_ATTACH.getValue()||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.ASSETS_PROJECT_ATTACH.getValue()||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.PATENT_RISK_ATTACH.getValue()||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.PATENT_SEARCH_RECORD_ATTACH.getValue()||
                    fileManage.getBusinessType() == FileBusinessTypeEnum.PATENT_PROPOSAL_THIRD_ATTACH.getValue()
            ) {
                String oldPath = fileManage.getFilePath();
                String path = oldPath.replace("upload", "http:\\\\" + currentIp + ":8090\\preview\\upload");
//                fileManage.setFilePath(path);
                item.put("filePath",path);
                item.put("path",path);
            }

            if (resultMap.containsKey(businessType)) {
                businessFiles = (List<Map<String,Object>>) resultMap.get(businessType);
            }
            businessFiles.add(item);
            resultMap.put(businessType, businessFiles);
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getOneFileManageInfo(String id) {
        FileManage fileManage = fileManageDao.selectById(id);
        Map<String, Object> resultMap = ObjectUtils.object2Map(fileManage);
        String currentIp = IPUtils.getCurrentIp();
        resultMap.put("fileUrl", fileManage.getFilePath().replace("upload", "http:\\\\" + currentIp + ":8090\\preview\\upload"));
        return resultMap;
    }

    @Override
    public void downloadFile(String fileId, HttpServletResponse response) {
        if (StringUtils.isEmpty(fileId)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "文件不存在");
        }
        FileManage fileInfo = fileManageDao.selectById(fileId);
        String name = fileInfo.getName();
        User operateUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String filePath = fileInfo.getFilePath();
        if (fileInfo.getBusinessType() == FileBusinessTypeEnum.DESIGN_STANDARD_MASTER.getValue()) {
            SPORequestHeaderDto spo = getSpo(operateUser);
            filePath = spoInterface.downloadFile(spo, fileInfo.getFilePath(), name);
        }
        File file = new File(filePath);
        if (!file.exists()) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, name + "文件不存在");
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + name);

        byte[] buffer = new byte[1024];
        try (FileInputStream fis = new FileInputStream(file);
             BufferedInputStream bis = new BufferedInputStream(fis)) {

            OutputStream os = response.getOutputStream();

            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            bis.close();
            fis.close();
        } catch (FileNotFoundException e) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, name + "文件不存在");
        } catch (IOException e) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "系统异常");
        }
    }

    @Override
    public void batchDownloadFile(String batchId, HttpServletResponse response) {
        if (StringUtils.isEmpty(batchId))
            return;
        List<String> idList = Arrays.asList(batchId.split(","));
        List<FileManage> list = fileManageDao.queryFileManageListByIds(idList);
        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        String date = TimeUtils.getDate("yyyy-MM-dd HH:mm:ss");
        String downloadName = "文件压缩包" + date + ".zip";
        response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");
        ZipOutputStream zipOs = null;
        DataOutputStream os = null;
        User operateUser = (User) ThreadlocalUtils.getCache("userInfo");
        try {
            zipOs = new ZipOutputStream(new BufferedOutputStream((OutputStream) response.getOutputStream()));
            zipOs.setMethod(8);
            for (FileManage fileInfo : list) {
                try {
                    String name = fileInfo.getName();
                    String path = TRANSFER_LOCAL_FILE_PATH + File.separator + name;
                    log.info("batchDownloadFile:[filePath:{}]", path);
                    String filePath = fileInfo.getFilePath();
                    if (fileInfo.getBusinessType() == FileBusinessTypeEnum.DESIGN_STANDARD_MASTER.getValue()) {
                        SPORequestHeaderDto spo = getSpo(operateUser);
                        filePath = spoInterface.downloadFile(spo, fileInfo.getFilePath(), name);
                    }
                    File file = new File(filePath);
                    if (!file.exists())
                        throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "文件不存在！");
                    zipOs.putNextEntry(new ZipEntry(name));
                    os = new DataOutputStream(zipOs);
                    FileInputStream fs = new FileInputStream(file);
                    byte[] b = new byte[100];
                    int length;
                    while ((length = fs.read(b)) != -1)
                        os.write(b, 0, length);
                    fs.close();
                    zipOs.closeEntry();
                } catch (Exception e) {
                    log.error("下载文件出错：[{}]", e.getMessage());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
                if (zipOs != null)
                    zipOs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void previewFile(String fileId, HttpServletResponse response) {
        // fileId 为服务器pdf文档id
        FileManage fileManage = fileManageDao.selectById(fileId);
//        String suffix = fileManage.getFileType();
//        if (!suffix.equals("txt") && !suffix.equals("doc") && !suffix.equals("docx") && !suffix.equals("xls") && !suffix.equals("xlsx") && !suffix.equals("ppt") && !suffix.equals("pptx")) {
//            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "文件格式不支持预览");
//        }
        if (ObjectUtils.isEmpty(fileManage)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "用户没有权限查看文件");
        }
        if (fileManage.getBusinessType() == FileBusinessTypeEnum.DESIGN_STANDARD_MASTER_PDF.getValue()) {
            // 获取当前用户所在组,判断用户组查看权限
            User operateUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
            Standard standard = standardDao.selectById(fileManage.getBusinessId());
            if (ObjectUtils.isEmpty(standard)) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "预览文件失败，标准主信息不存在！");
            }
            UserStandardPermission usp = userStandardPermissionDao.getUserStandard(operateUser.getId(), standard.getId());
            if (ObjectUtils.isEmpty(usp)) {
                UserGroupRelation relation = userGroupRelationDao.queryRelationByInfo(operateUser.getId(), standard.getGroupId());
                if (ObjectUtils.isEmpty(relation)) {
                    throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "预览文件失败，用户不具备该文件查看权限！");
                }
            }
        }

        String filePath = fileManage.getFilePath();
        try {
            File inputFile = new File(filePath);
            InputStream fileInputStream = new FileInputStream(inputFile);

            response.setHeader("Content-Disposition", "attachment;fileName=" + fileManage.getName());
            response.setContentType("multipart/form-data");
            OutputStream outputStream = response.getOutputStream();
            IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
//            File inputFile = new File(fileManage.getFilePath());
//            InputStream in = new FileInputStream(inputFile);
//            OutputStream outputStream = response.getOutputStream();
//            if (suffix.equals("png") || suffix.equals("jpg")) {
//                PdfConvertUtils.imgToPdf(inputStream, outputStream);
//            } else if (suffix.equals("ppt")) {
//                PdfConvertUtils.pptToPdf(inputStream, outputStream);
//            }

//            InputStream inputStream = FileConvertUtils.convertLocaleFile(fileManage.getFilePath(), suffix);
//            OutputStream outputStream = response.getOutputStream();

//            byte[] buff = new byte[1024];
//            //所读取的内容使用n来接收
//            int n;
//            //当没有读取完时,继续读取,循环
//            while ((n = inputStream.read(buff)) != -1) {
//                //将字节数组的数据全部写入到输出流中
//                outputStream.write(buff, 0, n);
//            }
//            //强制将缓存区的数据进行输出
//            outputStream.flush();
            //关流
            outputStream.close();
//            inputStream.close();
        } catch (Exception e) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "转换文件失败");
        }
        // 获取本地热度信息，存在更新热度，不存在新增热度信息
        FileTemporary temporary = fileTemporaryDao.selectById(fileId);
        if (ObjectUtils.isEmpty(temporary)) {
            FileTemporary newTemporary = new FileTemporary();
            newTemporary.setId(fileId);
            newTemporary.setFilePath(filePath);
            newTemporary.setHeat(1);
            fileTemporaryDao.insert(newTemporary);
        } else {
            temporary.setHeat(temporary.getHeat() + 1);
            fileTemporaryDao.updateById(temporary);
        }
    }

    @Override
    public void previewFileSpo(String fileId, HttpServletResponse response) {
        // 查询fileManage判断用户权限，获取文件路径
        FileManage fileManage = fileManageDao.selectById(fileId);
        if (ObjectUtils.isEmpty(fileManage)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "预览文件失败，文件不存在！");
        }
        // 获取当前用户所在组,判断用户组查看权限
        User operateUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        UserGroupRelation relation = userGroupRelationDao.queryRelationByInfo(operateUser.getId(), fileManage.getGroupId());
        if (ObjectUtils.isEmpty(relation)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "预览文件失败，用户不具备该文件查看权限！");
        }
        // 获取本地缓存，存在更新热度，不存在缓存数据到本地
        FileTemporary temporary = fileTemporaryDao.selectById(fileId);
        String filePath;
        if (ObjectUtils.isEmpty(temporary)) {
            SPORequestHeaderDto spo = getSpo(operateUser);
            filePath = spoInterface.downloadFile(spo, fileManage.getFilePath(), fileManage.getName());
            FileTemporary newTemporary = new FileTemporary();
            newTemporary.setId(fileId);
            newTemporary.setFilePath(filePath);
            newTemporary.setHeat(1);
            fileTemporaryDao.insert(newTemporary);
        } else {
            filePath = temporary.getFilePath();
            temporary.setHeat(temporary.getHeat() + 1);
            fileTemporaryDao.updateById(temporary);
        }

        try {
            File inputFile = new File(filePath);
            InputStream fileInputStream = new FileInputStream(inputFile);
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileManage.getName());
            response.setContentType("multipart/form-data");
            OutputStream outputStream = response.getOutputStream();
            IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
        } catch (Exception e) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "转换文件失败");
        }
    }

    @Override
    public void updateBusinessFile(String attachIds, String businessId) {
        List<FileManage> fileManageList = fileManageDao.queryFileManageList(businessId);
        if (StringUtils.isEmpty(attachIds) && fileManageList.size() == 0) {
            return;
        }
        List<String> oldFileIds = fileManageList.stream().map(FileManage::getId).collect(Collectors.toList());
        if (StringUtils.isEmpty(attachIds) && oldFileIds.size() > 0) {
            fileManageDao.deleteBatchIds(oldFileIds);
            return;
        }
        String[] fileIds = attachIds.split(",");
        List<String> commonList = new ArrayList<>();
        Map<String, Object> idMap = Arrays.stream(fileIds).collect(Collectors.toMap(Function.identity(), s -> 0));

        for (FileManage fileManage : fileManageList) {
            if (idMap.containsKey(fileManage.getId())) {
                commonList.add(fileManage.getId());
            }
        }
        fileManageDao.batchUpdateBusinessFile(fileIds, businessId);
        oldFileIds.removeAll(commonList);
        if (oldFileIds.size() > 0) {
            fileManageDao.deleteBatchIds(oldFileIds);
        }
    }

    @Override
    public Map<String, Map<String, String>> getFileMap(int businessType) {
        return fileManageDao.getFileMap(businessType);
    }

    /**
     * 上传文件到spo
     *
     * @param multipartRequest 文件流
     * @return 文件信息
     */
    @Override
    public Map<String, Object> uploadFileSpo(MultipartRequest multipartRequest) {
        String targetName = "";
        String originalName = "";
        String fileType = "";
        int businessType = Integer.valueOf(
                ((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().get("businessType")[0]);
        String groupId = "";
        if (((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().containsKey("group")) {
            groupId = ((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().get("group")[0];
        }
        UserGroup userGroup;
        if (StringUtils.isNotEmpty(groupId)) {
            userGroup = userGroupDao.selectById(groupId);
        } else {
            userGroup = userGroupDao.getDefault();
        }
        FileManage fileManage = new FileManage();
        User operateUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        if (ObjectUtils.isEmpty(userGroupRelationDao.queryRelationByInfo(operateUser.getId(), userGroup.getId()))) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "用户不具备该用户组权限！");
        }

        try {
            // 目标路径
            File file = new File(TEMP_LOCAL_FILE_PATH);
            // 如果文件目录不存在，就执行创建
            if (!file.isDirectory()) {
                file.mkdirs();
            }

            Iterator<String> fileListIterator = multipartRequest.getFileNames();
            MultipartFile multipartFile;
            String filePath = "";
            while (fileListIterator.hasNext()) {
                // 目标文件名称
                String str = fileListIterator.next();
                multipartFile = multipartRequest.getFile(str);
                originalName = multipartFile.getOriginalFilename();
                fileType = originalName.substring(originalName.lastIndexOf(".") + 1).toLowerCase();
                targetName = SnowFlake.nextIdStr();

                // 获取本地文件输入流
                InputStream stream = multipartFile.getInputStream();
                filePath = TEMP_LOCAL_FILE_PATH + targetName + "." + fileType;
                // 创建目标文件
                File targetFile = new File(filePath);
                FileOutputStream fos = new FileOutputStream(targetFile);

                // 写入目标文件
                byte[] buffer = new byte[1024 * 1024];
                int byteRead = 0;
                while ((byteRead = stream.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteRead);
                    fos.flush();
                }
                fos.close();
                stream.close();

                // 添加文件管理记录信息
                fileManage.setId(targetName);
                fileManage.setName(originalName);
                fileManage.setBusinessType(businessType);
                fileManage.setFileType(fileType);
                fileManage.setGroupId(userGroup.getId());
                fileManage.setOperateUser(operateUser.getId());
            }
            String targetSpoFolder = userGroup.getFolderPath();

            SPORequestHeaderDto spo = getSpo(operateUser);
            FileManage upInfo = spoInterface.uploadFile(spo, targetSpoFolder, filePath, targetName + "." + fileType);
            fileManage.setPreviewPath(upInfo.getPreviewPath());
            fileManage.setFilePath(upInfo.getFilePath());

            File deleteFile = new File(filePath);
            deleteFile.delete();
        } catch (AosException e) {
            log.error("读取文件失败" + e.getStackTrace());
            throw new AosException(e.getErrorCode(), e.getErrorMsg());
        } catch (Exception e) {
            log.error("读取文件失败" + e.getStackTrace());
            throw new AosException(ReturnCodes.HTTP_IMPORT_FAIL_READ_FILE);
        }

        fileManageDao.addFileManage(fileManage);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("fileName", targetName);
        resultMap.put("realName", originalName);
        resultMap.put("fileType", fileType);
        return resultMap;
    }

    /**
     * 上传文件到本地
     *
     * @param multipartRequest 文件流
     * @param businessType     文件类型
     * @return 文件信息
     */
    @Override
    public Map<String, Object> uploadFileTransfer(MultipartRequest multipartRequest, int businessType) {
        String targetName = "";
        String originalName = "";
        String fileType = "";
        String groupId = "";
        User operateUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        if (businessType == FileBusinessTypeEnum.DESIGN_STANDARD_MASTER.getValue()) {
            if (((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().containsKey("group")) {
                groupId = ((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().get("group")[0];
            }
            UserGroup userGroup;
            if (StringUtils.isNotEmpty(groupId)) {
                userGroup = userGroupDao.selectById(groupId);
            } else {
                userGroup = userGroupDao.getDefault();
            }
            if (ObjectUtils.isEmpty(userGroupRelationDao.queryRelationByInfo(operateUser.getId(), userGroup.getId()))) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "用户不具备该用户组权限！");
            }
        } else if (businessType == FileBusinessTypeEnum.BUTLER_TRAIN_MAIN.getValue()) {
            List<UserGroup> userGroupList = userGroupDao.queryUserGroupList();
            List<UserGroup> groupList = userGroupList.stream().filter(item -> StringUtils.equals(item.getFolderPath(), "/sites/DKSTest_01/Study Doc")).collect(Collectors.toList());
            if (ObjectUtils.isEmpty(groupList)) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "培训文档用户组不存在！");
            }
            groupId = groupList.get(0).getId();
        }

        FileManage fileManage = new FileManage();
        String filePath = "";
        try {
            // 目标路径
            File file = new File(TRANSFER_LOCAL_FILE_PATH);
            // 如果文件目录不存在，就执行创建
            if (!file.isDirectory()) {
                file.mkdirs();
            }

            Iterator<String> fileListIterator = multipartRequest.getFileNames();
            MultipartFile multipartFile;
            while (fileListIterator.hasNext()) {
                // 目标文件名称
                String str = fileListIterator.next();
                multipartFile = multipartRequest.getFile(str);
                originalName = multipartFile.getOriginalFilename();
                fileType = originalName.substring(originalName.lastIndexOf(".") + 1).toLowerCase();
                targetName = SnowFlake.nextIdStr();

                // 获取本地文件输入流
                InputStream stream = multipartFile.getInputStream();
                filePath = TRANSFER_LOCAL_FILE_PATH + targetName + "." + fileType;
                // 创建目标文件
                File targetFile = new File(filePath);
                FileOutputStream fos = new FileOutputStream(targetFile);

                // 写入目标文件
                byte[] buffer = new byte[1024 * 1024];
                int byteRead = 0;
                while ((byteRead = stream.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteRead);
                    fos.flush();
                }
                fos.close();
                stream.close();

                // 添加文件管理记录信息
                fileManage.setId(targetName);
                fileManage.setName(originalName);
                fileManage.setBusinessType(businessType);
                fileManage.setStatus(3);
                fileManage.setFileType(fileType);
                fileManage.setFilePath(filePath);
                fileManage.setGroupId(groupId);
                fileManage.setOperateUser(operateUser.getId());
            }

        } catch (AosException e) {
            log.error("读取文件失败" + e.getStackTrace());
            throw new AosException(e.getErrorCode(), e.getErrorMsg());
        } catch (Exception e) {
            log.error("读取文件失败" + e.getStackTrace());
            throw new AosException(ReturnCodes.HTTP_IMPORT_FAIL_READ_FILE);
        }

        fileManageDao.addFileManage(fileManage);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("id", targetName);
        resultMap.put("fileName", targetName);
        resultMap.put("realName", originalName);
        resultMap.put("fileType", fileType);
        resultMap.put("filePath", filePath);
        return resultMap;
    }

    /**
     * 上传文件到本地
     *
     * @param multipartRequest 文件流
     * @param businessType     文件类型
     * @return 文件信息
     */
    @Override
    public Map<String, Object> uploadFileLocal(MultipartRequest multipartRequest, int businessType) {
        String targetName = "";
        String originalName = "";
        String fileType = "";
        String groupId = "";
        User operateUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        if (businessType == FileBusinessTypeEnum.DESIGN_STANDARD_MASTER.getValue()) {
            if (((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().containsKey("group")) {
                groupId = ((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().get("group")[0];
            }
            UserGroup userGroup;
            if (StringUtils.isNotEmpty(groupId)) {
                userGroup = userGroupDao.selectById(groupId);
            } else {
                userGroup = userGroupDao.getDefault();
            }
            if (ObjectUtils.isEmpty(userGroupRelationDao.queryRelationByInfo(operateUser.getId(), userGroup.getId()))) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "用户不具备该用户组权限！");
            }
        }

        String folder = FileBusinessTypeEnum.getFolderByValue(businessType);
        FileManage fileManage = new FileManage();
        String filePath = "";
        try {
            // 目标路径
            File file = new File(folder);
            // 如果文件目录不存在，就执行创建
            if (!file.isDirectory()) {
                file.mkdirs();
            }

            Iterator<String> fileListIterator = multipartRequest.getFileNames();
            MultipartFile multipartFile;
            while (fileListIterator.hasNext()) {
                // 目标文件名称
                String str = fileListIterator.next();
                multipartFile = multipartRequest.getFile(str);
                originalName = multipartFile.getOriginalFilename();
                fileType = originalName.substring(originalName.lastIndexOf(".") + 1).toLowerCase();
                targetName = SnowFlake.nextIdStr();

                // 获取本地文件输入流
                InputStream stream = multipartFile.getInputStream();
                filePath = folder + targetName + "." + fileType;
                // 创建目标文件
                File targetFile = new File(filePath);
                FileOutputStream fos = new FileOutputStream(targetFile);

                // 写入目标文件
                byte[] buffer = new byte[1024 * 1024];
                int byteRead = 0;
                while ((byteRead = stream.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteRead);
                    fos.flush();
                }
                fos.close();
                stream.close();

                // 添加文件管理记录信息
                fileManage.setId(targetName);
                fileManage.setName(originalName);
                fileManage.setBusinessType(businessType);
                fileManage.setFileType(fileType);
                fileManage.setFilePath(filePath);
                fileManage.setGroupId(groupId);
                fileManage.setOperateUser(operateUser.getId());
            }

        } catch (AosException e) {
            log.error("读取文件失败" + e.getStackTrace());
            throw new AosException(e.getErrorCode(), e.getErrorMsg());
        } catch (Exception e) {
            log.error("读取文件失败" + e.getStackTrace());
            throw new AosException(ReturnCodes.HTTP_IMPORT_FAIL_READ_FILE);
        }

        fileManageDao.addFileManage(fileManage);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("id", targetName);
        resultMap.put("fileName", targetName);
        resultMap.put("realName", originalName);
        resultMap.put("fileType", fileType);
        resultMap.put("filePath", filePath);
        if (businessType == FileBusinessTypeEnum.USER_PICTURE.getValue()) {
            String currentIp = IPUtils.getCurrentIp();
            resultMap.put("fileUrl", fileManage.getFilePath().replace("upload", "http:\\\\" + currentIp + ":8090\\preview\\upload"));
        }
        return resultMap;
    }

    @Override
    public List<Map<String, Object>> batchUploadFileLocal(MultipartRequest multipartRequest, int businessType) {
        String groupId = "";
        User operateUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        if (businessType == FileBusinessTypeEnum.DESIGN_STANDARD_MASTER.getValue()) {
            if (((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().containsKey("group")) {
                groupId = ((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().get("group")[0];
            }
            UserGroup userGroup;
            if (StringUtils.isNotEmpty(groupId)) {
                userGroup = userGroupDao.selectById(groupId);
            } else {
                userGroup = userGroupDao.getDefault();
            }
            if (ObjectUtils.isEmpty(userGroupRelationDao.queryRelationByInfo(operateUser.getId(), userGroup.getId()))) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "用户不具备该用户组权限！");
            }
        }
        List<FileManage> fileManageList = new ArrayList<>();
        String folder = FileBusinessTypeEnum.getFolderByValue(businessType);

        try {
            // 目标路径
            File file = new File(folder);
            // 如果文件目录不存在，就执行创建
            if (!file.isDirectory()) {
                file.mkdirs();
            }
            List<MultipartFile> files = multipartRequest.getFiles("file");
            for (MultipartFile multipartFile : files) {
                FileManage fileManage = new FileManage();
                String originalName = multipartFile.getOriginalFilename();
                String fileType = originalName.substring(originalName.lastIndexOf(".") + 1).toLowerCase();
                String targetName = SnowFlake.nextIdStr();

                // 获取本地文件输入流
                InputStream stream = multipartFile.getInputStream();
                String filePath = folder + targetName + "." + fileType;
                // 创建目标文件
                File targetFile = new File(filePath);
                FileOutputStream fos = new FileOutputStream(targetFile);

                // 写入目标文件
                byte[] buffer = new byte[1024 * 1024];
                int byteRead = 0;
                while ((byteRead = stream.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteRead);
                    fos.flush();
                }
                fos.close();
                stream.close();

                // 添加文件管理记录信息
                fileManage.setId(targetName);
                fileManage.setName(originalName);
                fileManage.setBusinessType(businessType);
                fileManage.setFileType(fileType);
                fileManage.setFilePath(filePath);
                fileManage.setGroupId(groupId);
                fileManage.setOperateUser(operateUser.getId());
                fileManageList.add(fileManage);
            }
        } catch (AosException e) {
            log.error("读取文件失败" + e.getStackTrace());
            throw new AosException(e.getErrorCode(), e.getErrorMsg());
        } catch (Exception e) {
            log.error("读取文件失败" + e.getStackTrace());
            throw new AosException(ReturnCodes.HTTP_IMPORT_FAIL_READ_FILE);
        }

        if (ObjectUtils.isEmpty(fileManageList)) {
            return new ArrayList<>();
        }

        fileManageDao.insertBatch(fileManageList);

        String currentIp = "";
        if (businessType == FileBusinessTypeEnum.USER_PICTURE.getValue()) {
            currentIp = IPUtils.getCurrentIp();
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (FileManage fileManage : fileManageList) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("id", fileManage.getId());
            resultMap.put("fileName", fileManage.getId());
            resultMap.put("realName", fileManage.getName());
            resultMap.put("fileType", fileManage.getFileType());
            resultMap.put("filePath", fileManage.getFilePath());
            if (businessType == FileBusinessTypeEnum.USER_PICTURE.getValue()) {
                resultMap.put("fileUrl", fileManage.getFilePath().replace("upload", "http:\\\\" + currentIp + ":8090\\preview\\upload"));
            }
            resultList.add(resultMap);
        }

        return resultList;
    }

    @Override
    public Map<String, Object> uploadFileChimi(MultipartRequest multipartRequest) {
        String targetName = "";
        String originalName = "";
        String fileType = "";
        User operateUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        FileManage fileManage = new FileManage();
        try {
            // 目标路径
            File file = new File(FileBusinessTypeEnum.getFolderByValue(FileBusinessTypeEnum.CHIMI_CARD_ATTACH.getValue()));
            // 如果文件目录不存在，就执行创建
            if (!file.isDirectory()) {
                file.mkdirs();
            }

            Iterator<String> fileListIterator = multipartRequest.getFileNames();
            MultipartFile multipartFile;
            String filePath = "";
            while (fileListIterator.hasNext()) {
                // 目标文件名称
                String str = fileListIterator.next();
                multipartFile = multipartRequest.getFile(str);
                originalName = multipartFile.getOriginalFilename();
                fileType = originalName.substring(originalName.lastIndexOf(".") + 1).toLowerCase();
                targetName = SnowFlake.nextIdStr();

                // 获取本地文件输入流
                InputStream stream = multipartFile.getInputStream();
                filePath = FileBusinessTypeEnum.getFolderByValue(FileBusinessTypeEnum.CHIMI_CARD_ATTACH.getValue()) + targetName + "." + fileType;
                // 创建目标文件
                File targetFile = new File(filePath);
                FileOutputStream fos = new FileOutputStream(targetFile);

                // 写入目标文件
                byte[] buffer = new byte[1024 * 1024];
                int byteRead = 0;
                while ((byteRead = stream.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteRead);
                    fos.flush();
                }
                fos.close();
                stream.close();

                // 添加文件管理记录信息
                fileManage.setId(targetName);
                fileManage.setName(originalName);
                fileManage.setBusinessType(FileBusinessTypeEnum.CHIMI_CARD_ATTACH.getValue());
                fileManage.setFileType(fileType);
                fileManage.setFilePath(filePath);
                fileManage.setOperateUser(operateUser.getId());
            }

        } catch (AosException e) {
            log.error("读取文件失败" + e.getStackTrace());
            throw new AosException(e.getErrorCode(), e.getErrorMsg());
        } catch (Exception e) {
            log.error("读取文件失败" + e.getStackTrace());
            throw new AosException(ReturnCodes.HTTP_IMPORT_FAIL_READ_FILE);
        }

        fileManageDao.addFileManage(fileManage);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("fileName", targetName);
        resultMap.put("realName", originalName);
        resultMap.put("fileType", fileType);
        return resultMap;
    }

    @Override
    public void batchInvalidFile(String businessId) {
        fileManageDao.batchInvalidFile(businessId);
    }

    @Override
    public void moveFile(String fileId, int targetHost, String targetFilePath) {
        FileManage fileManage = fileManageDao.selectById(fileId);
        if (ObjectUtils.isEmpty(fileManage)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "文件移动失败，文件信息不存在！");
        }
        if (fileManage.getBusinessType() == FileBusinessTypeEnum.DESIGN_STANDARD_MASTER.getValue()) {
            // 获取当前用户所在组,判断用户组查看权限
            User operateUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
            UserGroupRelation relation = userGroupRelationDao.queryRelationByInfo(operateUser.getId(), fileManage.getGroupId());
//            if (ObjectUtils.isEmpty(relation)) {
//                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "文件移动失败，用户不具备该文件操作权限！");
//            }
            if (targetHost == 1) {
                UserGroup targetGroup = userGroupDao.selectById(targetFilePath);
                if (ObjectUtils.isEmpty(targetGroup)) {
                    throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "文件移动失败，目标文件夹不存在！");
                }
                UserGroupRelation targetRelation = userGroupRelationDao.queryRelationByInfo(operateUser.getId(), targetFilePath);
                if (ObjectUtils.isEmpty(targetRelation)) {
                    throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "文件移动失败，用户不具备目标文件夹操作权限！");
                }
                String tar = targetGroup.getFolderPath().replace(sharePoint.getSubsite(), "") + "/" + fileManage.getId() + "." + fileManage.getFileType();
                SPORequestHeaderDto spo = getSpo(operateUser);
                spoInterface.moveFile(spo, fileManage.getFilePath(), tar);
                fileManage.setFilePath(sharePoint.getMainsite() + sharePoint.getSubsite() + tar);
                fileManageDao.updateById(fileManage);
            } else {
                //todo 支持手动下载spo文件到RDKS
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "文件移动失败，暂不支持移动SPO文件至RDKS服务器！");
            }
        } else {
            //todo 支持手动上传本地文件到spo，支持本地文件修改目录地址
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "文件移动失败，暂不支持移动RDKS服务器文件！");
        }
    }

    @Override
    public int syncSpoFile() {
        User operateUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        SPORequestHeaderDto spo = getSpo(operateUser);
        List<UserGroup> userGroupList = userGroupDao.queryUserGroupList();
        List<FileManage> spoFileManageList = new ArrayList<>();
        for (UserGroup userGroup : userGroupList) {
            List<FileManage> dirFileList = spoInterface.getDirFileList(spo, userGroup.getFolderPath());
            for (FileManage firFile : dirFileList) {
                spoFileManageList.add(firFile);
            }
        }
        Map<String, Map<String, String>> dksFileMap = fileManageDao.getFilePathMap(FileBusinessTypeEnum.DESIGN_STANDARD_MASTER.getValue());
        List<FileManage> addFileList = new ArrayList<>();
        for (FileManage fileManage : spoFileManageList) {
            if (dksFileMap.containsKey(fileManage.getId())) {
                if (StringUtils.equals(fileManage.getFilePath(), dksFileMap.get(fileManage.getId()).get("filePath"))) {
                    continue;
                }
            }
            addFileList.add(fileManage);
        }
        if (addFileList.isEmpty()) {
            return 0;
        }
//        fileManageDao.insertBatch(addFileList);
        return addFileList.size();
    }

    @Override
    public void uploadLocalFileToSpo() {
        List<FileManage> pendingFileList = fileManageDao.getPendingFiles();
        for (FileManage file : pendingFileList) {
            System.out.println("file: " + file);
        }
        if (ObjectUtils.isEmpty(pendingFileList)) {
            log.info("暂无需要同步文件！");
            return;
        }
        List<FileManage> failedList = batchUploadSpo(pendingFileList);
        if (ObjectUtils.isEmpty(failedList)) {
            return;
        }
        fileManageDao.updateBatchById(failedList);
    }

    @Override
    public void cleanFiles() {

    }

    @Override
    public void reUploadFile(String id) {

    }

    @Override
    public void uploadFileThree(String id) {
        List<String> fileIds = Arrays.asList(id.split(","));
        List<FileManage> fileManageList = fileManageDao.queryFileManageListByIds(fileIds);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        List<DataPushRecord> dataPushRecordList = new ArrayList<>();
        for (FileManage fileManage : fileManageList) {
            if (fileManage.getBusinessType() != FileBusinessTypeEnum.DESIGN_STANDARD_MASTER_PDF.getValue()) {
                continue;
            }
            DataPushRecord dataPushRecord = new DataPushRecord();
            dataPushRecord.setId(SnowFlake.nextIdStr());
            dataPushRecord.setStatus(1);
            dataPushRecord.setOperateTime(currentTime);
            dataPushRecord.setContentOne(fileManage.getBusinessId());
            dataPushRecord.setContentTwo(fileManage.getName());
            dataPushRecordList.add(dataPushRecord);
        }
        if (ObjectUtils.isEmpty(dataPushRecordList)) {return;}
        dataPushDao.insertBatch(dataPushRecordList);
    }

    /**
     * 获取spo连接信息
     *
     * @param operateUser 当前操作用户
     * @return spo连接信息
     */
    private SPORequestHeaderDto getSpo(User operateUser) {
        SharePointHeader sharePointHeader = sharePointHeaderMapper.selectById("1");
        SPORequestHeaderDto spo = new SPORequestHeaderDto();
        if (ObjectUtils.isEmpty(sharePointHeader)) {
            spo = spoInterface.connectSPO(operateUser);
        } else {
            spo.setRequestDigest(sharePointHeader.getRequestDigest());
            spo.setRtFa(sharePointHeader.getRtFa());
            spo.setSecurityToken(sharePointHeader.getSecurityToken());
            spo.setFedAuth(sharePointHeader.getFedAuth());
        }
        return spo;
    }

    /**
     * 补全数据
     *
     * @param originalList 文档数据列表初始数据
     * @param startNum     查询起始数
     * @return 文档数据列表
     */
    private List<Map<String, Object>> completeResult(List<FileManage> originalList, int startNum) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (ObjectUtil.isEmpty(originalList)) {
            return resultList;
        }
        Map<String, Map<String, String>> userMap = userDao.getUserMap();
        String currentIp = IPUtils.getCurrentIp();
        int sort = startNum + 1;
        for (FileManage fileManage : originalList) {
            Map<String, Object> map = ObjectUtils.object2Map(fileManage);
            map.put("sort", sort);
            map.put("businessTypeName", FileBusinessTypeEnum.getNameByValue(fileManage.getBusinessType()));

            if (userMap.containsKey(fileManage.getOperateUser())) {
                map.put("userName", userMap.get(fileManage.getOperateUser()).get("name"));
            }
            map.put("viewUrl", fileManage.getFilePath().replace("upload", "http:\\\\" + currentIp + ":8090\\preview\\upload"));
            resultList.add(map);
            sort++;
        }
        return resultList;
    }

    /**
     * 批量上传文件到spo
     *
     * @param pendingList 待上传文件列表
     * @return 上传失败文件列表
     */
    private List<FileManage> batchUploadSpo(List<FileManage> pendingList) {
        User operateUser = userDao.getUserByAccount("admin");
        List<FileManage> failedList = new ArrayList<>();
        List<FileManage> successList = new ArrayList<>();
        List<UserGroup> userGroupList = userGroupDao.queryUserGroupList();
        // 用户组map
        Map<String, UserGroup> groupMap = new HashMap<>();
        for (UserGroup userGroup : userGroupList) {
            groupMap.put(userGroup.getId(), userGroup);
        }
        for (FileManage fileManage : pendingList) {
            String targetName = fileManage.getId();
//            String originalName = "";
            String fileType = fileManage.getFileType();

            UserGroup userGroup = groupMap.get(fileManage.getGroupId());
            try {
                // 目标路径
                String filePath = fileManage.getFilePath();
                String targetSpoFolder = userGroup.getFolderPath();

                SPORequestHeaderDto spo = getSpo(operateUser);
                FileManage upInfo = spoInterface.uploadFile(spo, targetSpoFolder, filePath, targetName + "." + fileType);
                fileManage.setPreviewPath(upInfo.getPreviewPath());
                fileManage.setFilePath(upInfo.getFilePath());
                fileManage.setStatus(0);
                successList.add(fileManage);
                File deleteFile = new File(filePath);
                deleteFile.delete();
            } catch (AosException e) {
                log.error("读取文件失败 aos " + e.getMessage());
                fileManage.setStatus(4);
                fileManage.setFailedTimes(fileManage.getFailedTimes() + 1);
                failedList.add(fileManage);
//                throw new AosException(e.getErrorCode(), e.getErrorMsg());
            } catch (Exception e) {
                log.error("读取文件失败" + e.getStackTrace());
                fileManage.setStatus(4);
                fileManage.setFailedTimes(fileManage.getFailedTimes() + 1);
                failedList.add(fileManage);
//                throw new AosException(ReturnCodes.HTTP_IMPORT_FAIL_READ_FILE);
            }
        }
        if (!successList.isEmpty()) {
            fileManageDao.updateBatchById(successList);
        }
        return failedList;
    }
}
